package com.shadt.cloud.apis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shadt.cloud.service.RecordApiService;
import com.shadt.cloud.vo.RecordVo;
import com.shadt.core.controller.BaseController;
import com.shadt.core.model.Json;

/**
 * api
 * 
 * @author SongR
 *
 */
@Controller
@RequestMapping(value="/api")
public class RecordApi extends BaseController{
	Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	RecordApiService service;
	/**
	 * 获取记录
	 * @version v2.0
	 * @param appname 平台名称
	 * @param keys key集合
	 * @param start 开始id号
	 * @param size 获取记录数
	 * @return
	 * 
	 */
	@ResponseBody
	@RequestMapping(value="/{version}/record/get",method={RequestMethod.GET,RequestMethod.POST})
	public Json getRecord(String appname ,String param,@PathVariable String version){
		Json j = new Json();
		switch(version){
			case "v2.0":
				j=getRecordV2(appname,param);
			break;
		}
		return j;
	}
	
	private Json getRecordV2(String appname ,String param){
		log.info("=="+param);
		param=	HtmlUtils.htmlUnescape(param);
		//param=param.replaceAll("&#39;", "\"").replaceAll("&quot;", "\"");
		log.info(param);
		Json j = new Json();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			JSONArray jarray = JSONArray.parseArray(param);
			for (int i = 0; i < jarray.size(); i++) {
				JSONObject o = jarray.getJSONObject(i);
				String key = o.getString("key");
				Integer start = o.getInteger("start")==null?0:o.getInteger("start");
				Integer size = o.getInteger("size")==null?10:o.getInteger("size");
				if(key.equals("")){
					j.setMsg("参数不正确");
					return j;
				}else{
					List<RecordVo> rvo = service.get(appname,key,start,size);
					if(rvo.size()>0){
						map.put(key, rvo);
					}else{
						//map.put(key, "该栏目暂无可用数据！");
					}
				}
			}
			j.setObj(map);
			j.setMsg("获取成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			j.setMsg("获取失败！");
			log.error("获取记录接口异常！",e);
		}
		return j;
	}
	
}
